import httpx
import re
import time
import hashlib

# 实例化一个可以发送h2协议的客户端
client = httpx.Client(http2=True)

# 弹幕接口
url = "https://api.bilibili.com/x/v2/dm/wbi/web/seg.so"
# 查询参数（oid、pid、w_rid、wts这四个参数是会变的）
params = {
    "type": "1",
    "oid": "1462784738",
    "pid": "1601588770",
    "segment_index": "1",
    "pull_mode": "1",
    "ps": "0",
    "pe": "120000",
    "web_location": "1315873",
    "w_rid": "ace2ca18309e8e7d1e32943f4f2c42a3",
    "wts": f"{int(time.time())}"
}

# 请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
}


# 要被MD5加密的字符串（其中的oid、pid参数代表你要获取哪一个b站视频的弹幕，这个参数在网页源代码里面可以找到）
string = f"oid=1462784738&pe=120000&pid=1601588770&ps=0&pull_mode=1&segment_index=1&type=1&web_location=1315873&wts={int(time.time())}" + "ea1db124af3c7062474693fa704f4ff8"
# MD5构造加密参数
md5 = hashlib.md5()
md5.update(string.encode('utf-8'))
w_rid = md5.hexdigest()
params['w_rid'] = w_rid

# 发送请求
resp = client.get(url=url, headers=headers, params=params)
resp.encoding = 'utf-8'

# 解析响应数据
for item in re.findall(r':(.*?)@', resp.text, re.S):
    print(item[1:])

